// LearningContentService.java
package com.example.gymlearning.service;

import com.example.gymlearning.entity.KnowledgePoint;
import com.example.gymlearning.entity.LearningContent;
import com.example.gymlearning.entity.QuizQuestion;
import com.example.gymlearning.mapper.LearningContentMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class LearningContentService {

    @Resource
    private KnowledgePointService knowledgePointService;

    @Resource
    private QuizQuestionService quizQuestionService;

    @Resource
    private LearningContentMapper learningContentMapper;

    /**
     * 获取知识点的学习内容
     */
    public Map<String, Object> getLearningContent(Long pointId) {
        Map<String, Object> content = new HashMap<>();

        try {
            // 1. 获取知识点基本信息
            KnowledgePoint point = knowledgePointService.queryById(pointId);
            if (point == null) {
                log.error("未找到知识点，ID: {}", pointId);
                return content;
            }

            String knowledgeType = point.getKnowledgeType();
            content.put("point", point);
            content.put("title", point.getTitle());
            content.put("description", point.getDescription());
            content.put("knowledgeType", knowledgeType);

            List<LearningContent> dbContents = learningContentMapper.findByPointId(pointId);
            boolean hasValidContent = false;
            
            if (dbContents != null && !dbContents.isEmpty()) {
                mergeContentFromDb(content, dbContents);
                // 检查是否有有效内容
                hasValidContent = hasValidContent(content, knowledgeType);
            }
            
            // 如果数据库没有有效内容，使用动态生成
            if (!hasValidContent) {
                generateDynamicContent(content, point, knowledgeType);
            }

            log.info("成功加载知识点学习内容，ID: {}, 类型: {}", pointId, knowledgeType);

        } catch (Exception e) {
            log.error("获取学习内容失败，pointId: {}", pointId, e);
            // 出错时尝试动态生成
            try {
                KnowledgePoint point = knowledgePointService.queryById(pointId);
                if (point != null) {
                    generateDynamicContent(content, point, point.getKnowledgeType());
                }
            } catch (Exception ex) {
                log.error("动态生成内容也失败", ex);
            }
        }

        return content;
    }
    
    /**
     * 检查是否有有效的内容
     */
    private boolean hasValidContent(Map<String, Object> content, String knowledgeType) {
        if ("概念理解型".equals(knowledgeType)) {
            Object conceptContentObj = content.get("conceptContent");
            Object analogyContentObj = content.get("analogyContent");
            return hasValidContentValue(conceptContentObj) || hasValidContentValue(analogyContentObj);
        } else if ("API学习型".equals(knowledgeType)) {
            Object overviewContentObj = content.get("overviewContent");
            Object usageContentObj = content.get("usageContent");
            return hasValidContentValue(overviewContentObj) || hasValidContentValue(usageContentObj);
        } else if ("代码实践型".equals(knowledgeType)) {
            Object conceptContentObj = content.get("conceptContent");
            Object visualizationContentObj = content.get("visualizationContent");
            return hasValidContentValue(conceptContentObj) || hasValidContentValue(visualizationContentObj);
        }
        // 默认检查是否有任何内容
        return content.values().stream()
                .anyMatch(this::hasValidContentValue);
    }
    
    /**
     * 检查内容值是否有效（支持字符串和对象格式）
     */
    private boolean hasValidContentValue(Object value) {
        if (value == null) {
            return false;
        }
        if (value instanceof String) {
            return !((String) value).trim().isEmpty();
        }
        if (value instanceof Map) {
            @SuppressWarnings("unchecked")
            Map<String, Object> map = (Map<String, Object>) value;
            // 检查对象中是否有richContent或description
            Object richContent = map.get("richContent");
            Object description = map.get("description");
            return (richContent != null && richContent instanceof String && !((String) richContent).trim().isEmpty()) ||
                   (description != null && description instanceof String && !((String) description).trim().isEmpty());
        }
        return false;
    }

    /**
     * 根据知识点类型生成动态内容
     * 只在字段不存在或为空时才设置
     */
    private void generateDynamicContent(Map<String, Object> content, KnowledgePoint point, String knowledgeType) {
        String title = point.getTitle();

        switch (knowledgeType) {
            case "概念理解型":
                if (!hasValidString(content, "conceptContent")) {
                    content.put("conceptContent", generateConceptContent(title));
                }
                if (!hasValidString(content, "analogyContent")) {
                    content.put("analogyContent", generateAnalogyContent(title));
                }
                break;
            case "API学习型":
                if (!hasValidString(content, "overviewContent")) {
                    content.put("overviewContent", generateOverviewContent(title));
                }
                if (!hasValidString(content, "usageContent")) {
                    content.put("usageContent", generateUsageContent(title));
                }
                break;
            case "代码实践型":
                if (!hasValidString(content, "conceptContent")) {
                    content.put("conceptContent", generateConceptContent(title));
                }
                if (!hasValidString(content, "visualizationContent")) {
                    content.put("visualizationContent", generateVisualizationContent(title));
                }
                break;
            default:
                if (!hasValidString(content, "conceptContent")) {
                    content.put("conceptContent", generateDefaultConceptContent(title));
                }
                if (!hasValidString(content, "analogyContent")) {
                    content.put("analogyContent", generateDefaultAnalogyContent(title));
                }
        }
    }
    
    /**
     * 检查Map中是否有有效的字符串值
     */
    private boolean hasValidString(Map<String, Object> content, String key) {
        Object value = content.get(key);
        return value != null && value instanceof String && !((String) value).trim().isEmpty();
    }

    /**
     * 获取知识点的测验题目（用于学习页面）
     * 学习页面只显示选择题和填空题
     */
    public List<QuizQuestion> getLearningQuizQuestions(Long pointId) {
        try {
            List<QuizQuestion> allQuestions = quizQuestionService.getQuestionsByKnowledgePointId(pointId);

            // 过滤出适合学习页面的题目类型（选择题和填空题）
            return allQuestions.stream()
                    .filter(q -> isLearningQuestionType(q.getQuestionType()))
                    .collect(java.util.stream.Collectors.toList());

        } catch (Exception e) {
            log.error("获取学习页面题目失败，pointId: {}", pointId, e);
            return java.util.Collections.emptyList();
        }
    }

    /**
     * 获取知识点的练习题目（用于练习页面）
     * 练习页面显示所有类型的题目
     */
    public List<QuizQuestion> getPracticeQuizQuestions(Long pointId) {
        try {
            return quizQuestionService.getQuestionsByKnowledgePointId(pointId);
        } catch (Exception e) {
            log.error("获取练习页面题目失败，pointId: {}", pointId, e);
            return java.util.Collections.emptyList();
        }
    }

    /**
     * 判断题目类型是否适合学习页面
     */
    private boolean isLearningQuestionType(String questionType) {
        return "single".equals(questionType) ||
                "multiple".equals(questionType) ||
                "fill-blank".equals(questionType);
    }

    private void mergeContentFromDb(Map<String, Object> content, List<LearningContent> entries) {
        Map<String, List<LearningContent>> grouped = entries.stream()
                .collect(Collectors.groupingBy(e -> e.getStageType() == null ? "general" : e.getStageType()));

        grouped.forEach((stageType, items) -> {
            LearningContent first = items.get(0);
            String key = mapStageTypeToKey(stageType);
            
            // 检查是否有有效内容
            String richContent = first.getRichContent();
            String description = first.getDescription();
            boolean hasRichContent = richContent != null && !richContent.trim().isEmpty();
            boolean hasDescription = description != null && !description.trim().isEmpty();
            
            if (hasRichContent || hasDescription) {
                // 如果有richContent，返回对象格式（前端期望的格式）
                if (hasRichContent) {
                    Map<String, Object> contentObj = new HashMap<>();
                    contentObj.put("title", first.getTitle());
                    contentObj.put("subtitle", first.getSubtitle());
                    contentObj.put("description", description);
                    contentObj.put("richContent", richContent);
                    content.put(key, contentObj);
                } else {
                    // 如果只有description，返回字符串格式
                    content.put(key, description);
                }
            }
            // 如果内容为空，不设置该字段，让动态生成来填充
        });
    }

    private String mapStageTypeToKey(String stageType) {
        if (stageType == null) {
            return "conceptContent";
        }
        switch (stageType) {
            // 英文stage_type
            case "concept":
                return "conceptContent";
            case "analogy":
                return "analogyContent";
            case "example":
                return "exampleContent";
            case "overview":
                return "overviewContent";
            case "usage":
                return "usageContent";
            case "practice":
            case "coding":
                return "practiceContent";
            case "visualization":
                return "visualizationContent";
            // 中文stage_type（数据库中的值）
            case "核心拆解":
                return "conceptContent";
            case "类比记忆":
                return "analogyContent";
            case "实战示例":
                return "exampleContent";
            case "概览":
            case "API概览":
                return "overviewContent";
            case "用法":
            case "API用法":
                return "usageContent";
            case "实践":
            case "代码实践":
                return "practiceContent";
            case "可视化":
                return "visualizationContent";
            default:
                // 如果都不匹配，尝试根据包含的关键字判断
                if (stageType.contains("核心") || stageType.contains("拆解") || stageType.contains("概念")) {
                    return "conceptContent";
                } else if (stageType.contains("类比") || stageType.contains("记忆")) {
                    return "analogyContent";
                } else if (stageType.contains("示例") || stageType.contains("实战") || stageType.contains("例子")) {
                    return "exampleContent";
                } else if (stageType.contains("概览") || stageType.contains("overview")) {
                    return "overviewContent";
                } else if (stageType.contains("用法") || stageType.contains("usage")) {
                    return "usageContent";
                } else if (stageType.contains("实践") || stageType.contains("practice") || stageType.contains("coding")) {
                    return "practiceContent";
                } else if (stageType.contains("可视化") || stageType.contains("visualization")) {
                    return "visualizationContent";
                }
                return "conceptContent"; // 默认返回conceptContent
        }
    }

    // ===== 动态内容生成方法 =====

    private String generateConceptContent(String title) {
        if (title.contains("IoC") || title.contains("依赖注入")) {
            return "IoC（控制反转）是一种设计原则，用来将对象的创建和绑定从使用它们的代码中解耦。在传统的程序设计中，我们直接在代码中创建对象，而使用IoC后，对象的创建和管理由容器负责，我们只需要定义好依赖关系即可。";
        } else if (title.contains("多线程")) {
            return "多线程允许程序同时执行多个任务，提高CPU利用率和程序响应性。通过创建多个线程，可以让程序在执行耗时操作时仍能响应用户交互，或者利用多核CPU的优势并行处理任务。";
        } else if (title.contains("集合")) {
            return "集合框架提供了一系列用于存储和操作数据组的数据结构。不同的集合类有不同的特性和适用场景，如List适合有序存储，Set适合去重存储，Map适合键值对存储。";
        }
        return "让我们深入理解 " + title + " 的核心概念和基本原理。这个概念在软件开发中扮演着重要角色，掌握它对于提升编程能力至关重要。";
    }

    private String generateAnalogyContent(String title) {
        if (title.contains("IoC") || title.contains("依赖注入")) {
            return "IoC就像餐厅的点餐系统：传统方式是你自己去厨房点菜（直接创建对象），而IoC是你告诉服务员（容器），服务员帮你协调一切。你不需要关心菜是怎么做的，只需要享受美食（使用对象）。";
        } else if (title.contains("多线程")) {
            return "多线程就像厨房里的多位厨师：单线程就像只有一位厨师，他必须一道菜一道菜地做；而多线程就像有多位厨师，他们可以同时准备不同的菜品，大大提高效率。";
        } else if (title.contains("集合")) {
            return "集合就像不同的储物容器：List就像书架，书按顺序摆放；Set就像储物箱，每个物品只放一次；Map就像带标签的储物柜，通过标签快速找到物品。";
        }
        return "想象一下 " + title + " 就像日常生活中的某个场景，通过这种类比可以帮助你更好地理解这个抽象概念的实际应用和意义。";
    }

    private String generateOverviewContent(String title) {
        return "了解" + title + "的主要功能和用途。这个API提供了强大的功能来帮助你更高效地完成开发任务。";
    }

    private String generateUsageContent(String title) {
        return "学习" + title + "的实际使用方法和最佳实践。掌握这些用法可以让你在项目中更加得心应手。";
    }

    private String generateVisualizationContent(String title) {
        return "通过可视化方式理解" + title + "的执行过程和内部机制。";
    }

    private String generateDefaultConceptContent(String title) {
        return "学习" + title + "的核心概念和基本原理。";
    }

    private String generateDefaultAnalogyContent(String title) {
        return "通过类比理解" + title + "的实际应用场景。";
    }
}